package com.haoyeteng.sxbd.modular.business.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.haoyeteng.sxbd.core.base.controller.BaseController;
import com.haoyeteng.sxbd.core.common.constant.factory.PageFactory;
import com.haoyeteng.sxbd.modular.business.model.Category;
import com.haoyeteng.sxbd.modular.business.service.ICategoryService;
import com.haoyeteng.sxbd.modular.common.service.IUploadService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.haoyeteng.sxbd.core.base.model.ResponseResult;
import com.haoyeteng.sxbd.core.common.annotion.Permission;

import java.io.IOException;
import java.util.*;

import com.haoyeteng.sxbd.core.log.LogObjectHolder;
import com.haoyeteng.sxbd.modular.business.model.News;
import com.haoyeteng.sxbd.modular.business.service.INewsService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 新闻表控制器
 *
 * @author haoyeteng
 * @Date 2019-06-11 20:56:10
 */
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController {

    private String PREFIX = "/business/news/";

    @Autowired
    private INewsService newsService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IUploadService uploadService;

    /**
     * 跳转到新闻表首页
     */
    @RequestMapping("")
    public String index(Model model) {
        List<Category> categories = categoryService.selectList(new EntityWrapper<Category>());
        model.addAttribute("categories", categories);
        return PREFIX + "news.html";
    }

    /**
     * 跳转到添加新闻表
     */
    @RequestMapping("/news_add")
    public String newsAdd(Model model) {
        List<Category> categories = categoryService.selectList(new EntityWrapper<Category>());
        model.addAttribute("categories", categories);
        return PREFIX + "news_add.html";
    }

    /**
     * 跳转到修改新闻表
     */
    @RequestMapping("/news_update/{newsId}")
    public String newsUpdate(@PathVariable Integer newsId, Model model) {
        List<Category> categories = categoryService.selectList(new EntityWrapper<Category>());
        model.addAttribute("categories", categories);
        News news = newsService.selectById(newsId);
        model.addAttribute("item",news);
        LogObjectHolder.me().set(news);
        return PREFIX + "news_edit.html";
    }

    /**
     * 获取新闻表列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    @Permission
    public ResponseResult<Object> list(Integer categoryId , String newsName) {
        Page<News> page = new PageFactory<News>().defaultPage();
        List<Map<String,Object>> newses = newsService.selectNewses(page, categoryId, newsName);
    	ResponseResult<Object> result = new ResponseResult<Object>();
        result.setData(newses);
 		result.setCount(page.getTotal());
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }

    /**
     * 新增新闻表
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @Permission
    public Object add(@RequestBody News news) {
        Date date = new Date();
        news.setCreateTime(date);
        news.setUpdateTime(date);
        news.setFlag(1);
        newsService.insert(news);
        return SUCCESS_TIP;
    }

    /**
     * 删除新闻表
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Permission
    public Object delete(@RequestParam Integer newsId) {
        newsService.deleteById(newsId);
        return SUCCESS_TIP;
    }

    /**
     * 修改新闻表
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @Permission
    public Object update(@RequestBody News news) {
        news.setUpdateTime(new Date());
        newsService.updateById(news);
        return SUCCESS_TIP;
    }

    /**
     * 新闻表详情
     */
    @RequestMapping(value = "/detail/{newsId}")
    @ResponseBody
    public Object detail(@PathVariable("newsId") Integer newsId) {
        return newsService.selectById(newsId);
    }

    /**
     * 上传设备 新增设备 鉴定图片
     * @param uploadImage 上传文件
     * @throws IOException io
     */
    @RequestMapping(value = "/toUploadImage", method = RequestMethod.POST)
    @ResponseBody
    public Object toUploadImage(@RequestParam("uploadImage") MultipartFile uploadImage, HttpServletRequest request,
                                HttpServletResponse response) throws IOException {
        Map<String,Object> map = new HashMap<>(16);
        String fileName = uploadImage.getOriginalFilename();
        int size = request.getContentLength();
        if (!fileName.matches("(.*)\\.(jpg|bmp|gif|jpeg|png|JPG|BMP|GIF|JPEG|PNG)$")) {
            map.put("errno", -1);
            map.put("msg","上传图片格式不正确,请上传图片后缀名为（jpg、bmp、gif、jpeg、png、JPG、BMP、GIF、JPEG、PNG）格式的图片，不区分大小写");
        } else if (size > 10485760) {
            map.put("errno", -1);
            map.put("msg","上传的图片不能大于10M");
        } else {
            try {
                Long time = System.currentTimeMillis();
                int random = (int) (Math.random() * 10000);
                String newFileName = time.toString() + random + fileName.substring(fileName.lastIndexOf("."));
                String fileid = uploadService.addFile(uploadImage, newFileName);
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                        + request.getContextPath() + "/static/file/" + fileid + ".shtml";
                List<String> data = new ArrayList<>();
                data.add(url);
                map.put("errno", 0);
                map.put("data", data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
